from django.shortcuts import render

# Create your views here.
from django.http import HttpResponse
import json
import requests
from bs4 import BeautifulSoup
import re
#返回结果格式
def resultData():
    data = {
        "websiteType" : 0,
        "titleName":"",
        "titleHref": "",
        "source":"",
        "label":"",
        "volume":"",
        "summary":"",
        "detailId":'',
        "publishTime" :"",
        "category" : "",
        "quote" :"",
        "abstract": "",
        "doi": "",
        "downLoad": "",
        "keyword": [],
        "author": [],

    }
    return data


def formData(response):
    allData = []
    # 获取sid并且更新返回
    soup = BeautifulSoup(response.text, "html5lib")

    trs = soup.select(".s_table > tbody > tr")[1:]

    page_number1 = soup.select("#id_grid_total")[0].text
    page_number2 = re.sub('[^0-9]', ' ', page_number1).strip().replace(" ", '')

    for tr in trs:


        tempData = resultData()

        tempData["websiteType"] = 1

        try:
            tempData["titleName"] = tr.select("td")[1].select("a")[0].text.strip()
        except:
            raise
        try:
            tempData["titleHref"] = tr.select("td")[1].select("a")[0]["href"]
        except:
            pass
        try:
            tempData["author"] = [tr.select("td")[2].text]

        except:
            pass


        allData.append(tempData)

    return allData, page_number2

def buildingParameters(data):
    # 主题、题名或关键词、题名、第一作者、作者单位、作者、关键词、摘要、基金、DOI
    # 主题:()*作者:()
    typeCorr = {
        "SU": "主题",
        "TI": "题名",
        "AU": "作者",
        "AF": "作者单位",
        "AB": "摘要",
        "KY": "关键词",
    }
    logCorr = {
        "and": "*",
        "or": "+",
        "not": "^",
        "###":"###"
    }

    data["log"].append("###")

    tempStr = []
    for i in range(len(data["values"])):

        try:
            strr = typeCorr[data["type"][i]] + ":" + "(" + data["values"][i] + ")" + "{}".format(logCorr[data["log"][i]])
            tempStr.append(strr)
        except:
            continue

    strr = ''
    for value in tempStr:
        strr += value

    return strr.strip().strip("#").strip()


def getData(keyword):


    headers = {
        'Connection': 'keep-alive',
        'Cache-Control': 'max-age=0',
        'Origin': 'http://dbpub.cnki.net',
        'Upgrade-Insecure-Requests': '1',
        'Content-Type': 'application/x-www-form-urlencoded',
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36',
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
        'Referer': 'http://dbpub.cnki.net/grid2008/Dbpub/Brief.aspx?ID=gxdb',
        'Accept-Encoding': 'gzip, deflate',
        'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
    }

    params = (
        ('ID', 'gxdb'),
    )

    data = [
        ('ID', 'gxdb'),
        ('hdnSearchType', ''),
        ('hdnIsAll', 'false'),
        ('NaviField', '\u56FD\u5B66\u5206\u7C7B\u4EE3\u7801'),
        ('NaviDatabaseName', 'GXDB_FLCLS'),
        ('systemno', ''),
        ('systemno', ',,,,,'),
        ('hdnFathorCode', 'sysAll'),
        ('selectbox', 'A'),
        ('selectbox', 'B'),
        ('selectbox', 'C'),
        ('selectbox', 'D'),
        ('selectbox', 'E'),
        ('selectbox', 'F'),
        ('strNavigatorValue', ',A,B,C,D,E,F'),
        ('strNavigatorName',
         ',\u7ECF\u90E8,\u53F2\u90E8,\u5B50\u90E8,\u96C6\u90E8,\u4E1B\u4E66,\u901A\u4FD7\u5C0F\u8BF4'),
        ('singleleafcode', ''),
        ('searchAttachCondition', ''),
        ('SearchQueryID', '11'),
        ('SearchFieldRelationDirectory', ''),
        ('updateTempDB', ''),
        ('bCurYearTempDB', '0'),
        ('fieldtips', ''),
        ('advancedfield1', '\u4E66\u540D'),
        ('advancedvalue1', keyword),
        ('imageField.x', '30'),
        ('imageField.y', '9'),
        ('searchmatch', '0'),
        ('order', 'dec'),
        ('RecordsPerPage', '20'),
        ('hdnUSPSubDB',
         '\u671D\u4EE3\u9009\u62E9/\u671D\u4EE3\u6570\u5B57\u4EE3\u7801,+1+2+3+4+5+6+7+8+9+10+11+12+13+14+15+16+,16,16'),
        ('TableType', 'PY'),
        ('display', 'chinese'),
        ('encode', 'gb'),
        ('TablePrefix', 'GXDB'),
        ('View', '\u56FD\u5B66\u5B9D\u5178\u6570\u636E\u5E93'),
        ('yearFieldName', '\u5E74'),
        ('userright', ''),
        ('VarNum', '1'),
        ('lastpage', '18'),
        ('RecordsPerPage2', '20'),
        ('classtype', ''),
        ('QueryID', '11'),
        ('turnpage', ''),
        ('curpage', '1'),
        ('curpage1', '1'),
        ('curpage2', '1'),
    ]

    response = requests.post('http://dbpub.cnki.net/grid2008/Dbpub/Brief.aspx', headers=headers, params=params,data=data)

    result,allNum = formData(response)


    return result,allNum

def index(request):
    data = json.loads(request.POST.get('data', '1'))
    # paramStrs = buildingParameters(data)

    allData,allNUm = getData(data["values"][0])

    return HttpResponse(json.dumps({
        "collection": allData,
        "allNum": 0
    }), content_type="application/json")
